<?php

namespace app\common;

class ApiResponse
{
    // 定义状态码对应的信息
    protected static $codeMessage = [
        200 => '操作成功',
        400 => '参数错误',
        // 更多的状态码和对应的信息...
    ];

    // 返回成功的响应
    public static function success($data = null, $message)
    {
        return self::response(200, $message, $data);
    }

    // 返回带有列表数据的成功响应
    public static function successList($data = null, $message)
    {
        if (getType($data) == "object") {
            $data = $data->toArray();
        }
        $isPage = false;
        if (isset($data['total']) && isset($data['current_page'])) {
            $isPage = true;
        }
        $resData = [];
        $pagination = null;

        if ($isPage && isset($data['data'])) {
            $resData = $data['data'];
            $pagination = [
                'total' => $data["total"] ?? "0",
                'per_page' => $data["per_page"] ?? "0",
                'current_page' => $data["current_page"] ?? "0",
                'last_page' => $data["last_page"] ?? "0"
            ];
        } else {
            $resData = $data;
        }
        return self::response(200, $message, $resData, $pagination);
    }


    // 构造响应数据
    protected static function response($code, $message = null, $data = null ,$pagination = null)
    {
        $result = [
            'code' => $code,
            'message' => $message ?? self::$codeMessage[$code] ?? '',
            'data' => $data
        ];
        if(!empty($pagination)){
            $result['pagination'] = $pagination;
        }
        return json($result);
    }

}